﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using CWB.Web.Configuration;
using System.Threading;
using System.Globalization;

namespace CWB.WebSite.ToolPages
{
    public partial class LanguageJsGenerator : ToolPageBase
    {
        private static string ParseHTML(string rawHTML)
        {
            int start = rawHTML.IndexOf('>') + 1;
            int length = rawHTML.LastIndexOf('<') - start;
            string html = rawHTML.Substring(start, length).Trim();
            return RemoveSpace(html);
        }

        private static string RemoveSpace(string str)
        {
            StringBuilder builder = new StringBuilder(str.Length);
            bool isSpace = false;
            foreach (var c in str)
            {
                switch (c)
                {
                    case ' ':
                        if (!isSpace)
                        {
                            isSpace = true;
                            builder.Append(c);
                        }
                        break;
                    case '\r':
                    case '\n':
                        break;
                    default:
                        isSpace = false;
                        builder.Append(c);
                        break;
                }
            }
            return builder.ToString();
        }

        private string GetDirectory(string webPath)
        {
            string path = Server.MapPath(webPath);
            DirectoryInfo directory = new DirectoryInfo(path);
            if (directory.Exists)
            {
                directory.Create();
            }
            return path;
        }

        protected override void Render(HtmlTextWriter writer)
        {
#if DEBUG

            foreach (var language in AppConfigManager.LanguageInfos)
            {
                Response.Write(string.Format("<h2>{0}</h2>", language.CultureName));
                string directory = GetDirectory("~/CDN/Js/Language/");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(language.CultureName);
                StringWriter stringWriter = new StringWriter();
                using (HtmlTextWriter languagedWriter = new HtmlTextWriter(stringWriter))
                {
                    var divControl = js;
                    string filePath = string.Format(@"{0}{1}.js", directory, language.CultureName);
                    divControl.RenderControl(languagedWriter);
                    string html = ParseHTML(languagedWriter.InnerWriter.ToString());
                    File.WriteAllText(filePath, html);
                    Response.Write(html);
                }
            }

#endif
            base.Render(writer);
        }
    }
}
